package com.lmx.persistence.service;

import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.common.BaseCrudServiceImpl;
import com.lmx.repoDomain.tmodel.PersonLocation;

@Service(value = "personLocationService")
public class PersonLocationServiceImpl extends
		BaseCrudServiceImpl<PersonLocation> implements PersonLocationService {

	@SuppressWarnings("unchecked")
	@Override
	public List<PersonLocation> findRowData(Long dateValue, Integer limit,
			Integer start, Long TenantId) {
		Query query = this.buildQueryByDate(dateValue, TenantId, false);
		if (limit != null) {
			query.setMaxResults(limit);
		}
		if (start != null) {
			query.setFirstResult(start);
		}
		return query.getResultList();
	}

	@Override
	public Long getDataCount(Long dateValue, Long tenantId) {
		Query query = this.buildQueryByDate(dateValue, tenantId, true);
		return (Long) query.getResultList().get(0);
	}

	@Override
	public List<PersonLocation> findRowDataByEmployee(Long employeeId,
			Long generatTime) {
		Integer start = CommonUtil.getDayBegin(new Date(generatTime));
		Integer end = CommonUtil.getDayBegin(new DateTime(generatTime)
				.plusDays(1).toDate());
		return this.findRowDataByEmployee(employeeId, start, end);
	}

	@Override
	public List<PersonLocation> findRowDataByEmployee(Long employeeId,
			Long startTime, Long endTime) {
		Integer startTimeInt = (int) (startTime / 1000);
		Integer endTimeInt = (int) (endTime / 1000);
		return this.findRowDataByEmployee(employeeId, startTimeInt, endTimeInt);
	}

	@SuppressWarnings("unchecked")
	private List<PersonLocation> findRowDataByEmployee(Long employeeId,
			Integer startTime, Integer endTime) {
		String queryStr = "from PersonLocation as a where createDateTime >= :start and createDateTime < :end and employee.id=:employeeId and room is not null order by  createDateTime asc";
		return super.em.createQuery(queryStr.toString())
				.setParameter("employeeId", employeeId)
				.setParameter("start", startTime).setParameter("end", endTime)
				.getResultList();
	}

	/**
	 * 根据时间构建查询query
	 *
	 * @author ytche
	 * @param dateValue
	 * @param tenantId
	 * @param count
	 *            是否是统计总数
	 * @return
	 * @date 2017年6月6日 下午3:56:45
	 */
	private Query buildQueryByDate(Long dateValue, Long tenantId, Boolean count) {
		Date date = new Date(dateValue);
		Date nextDay = new DateTime(date).plusDays(1).toDate();
		Integer dayBegin = CommonUtil.getDayBegin(date);
		Integer nextDayBegin = CommonUtil.getDayBegin(nextDay);
		String queryStr = count ? "select count(p) " : "";
		queryStr += " from PersonLocation as p where p.createDateTime > ?1 and p.createDateTime < ?2 and p.delStatus =0 and p.tenant.id= ?3 ";
		return super.em.createQuery(queryStr).setParameter(1, dayBegin)
				.setParameter(2, nextDayBegin).setParameter(3, tenantId);
	}

}
